package com.vvv.shortlink.project.handler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vvv.shortlink.project.dao.entity.LinkDO;
import com.vvv.shortlink.project.dao.mapper.LinkMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import static com.vvv.shortlink.project.constant.LinkConstant.HTTP_TIMEOUT;
import static com.vvv.shortlink.project.constant.LinkConstant.XIAO_HEI_ZI_URL;

/**
 * @author vvv
 * @date 2024-03-04 17 57
 * discription
 */
@Component
@RequiredArgsConstructor
public class LinkServiceAsyncHandler {

    private final LinkMapper linkMapper;

    /**
     * 异步获取获取原始链接的图标
     *
     * @param userId 创建人
     * @param gid 分组标识
     * @param fullShortUrl 完整短链
     * @param originUrl 原始链接
     */
    @Async
    public void fetchFaviconFuture(Long userId, String gid, String fullShortUrl, String originUrl) {
        LinkDO linkDO = new LinkDO();
        LambdaUpdateWrapper<LinkDO> updateWrapper = Wrappers.lambdaUpdate(LinkDO.class)
                .eq(LinkDO::getUserId, userId)
                .eq(LinkDO::getGid, gid)
                .eq(LinkDO::getFullShortUrl, fullShortUrl);
        HttpURLConnection connection = null;
        try {
            URL targetUrl = new URL(originUrl);
            connection = (HttpURLConnection) targetUrl.openConnection();
            // 禁止自动处理重定向
            connection.setInstanceFollowRedirects(false);
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            // 如果是重定向响应码
            if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                // 重获取重定向的URL
                String redirectUrl = connection.getHeaderField("Location");
                // 如果重定向URL不为空
                if (redirectUrl != null) {
                    URL newUrl = new URL(redirectUrl);
                    // 打开新的连接
                    connection = (HttpURLConnection) newUrl.openConnection();
                    // 设置请求方法为GET
                    connection.setRequestMethod("GET");
                    // 超时时间
                    connection.setConnectTimeout(HTTP_TIMEOUT);
                    connection.setReadTimeout(HTTP_TIMEOUT);
                    // 连接
                    connection.connect();
                    // 获取新的响应码
                    responseCode = connection.getResponseCode();
                }
            }
            if (HttpURLConnection.HTTP_OK == responseCode) {
                Document document = Jsoup.connect(originUrl).get();
                Element faviconLink = document.select("link[rel~=(?i)^(shortcut )?icon]").first();
                if (faviconLink != null) {
                    linkDO.setFavicon(faviconLink.attr("abs:href"));
                } else {
                    linkDO.setFavicon(XIAO_HEI_ZI_URL);
                }
            }
        } catch (IOException e) {
            linkDO.setFavicon(XIAO_HEI_ZI_URL);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        linkMapper.update(linkDO, updateWrapper);
    }
}
